<?php

class Aggregators extends Controller {

    function search() {
        if (isset($_POST["submit"])) {
            $User = new User();
            $query = mysql_real_escape_string($_POST["query"]);

            $result = $this->Aggregator->find_users($query);
            $this->set("user_result", $result);

            $photos = $this->Aggregator->find_photos($query);
            $count = count($photos);

            for ($i = 0; $i < $count; $i++) {
                $access_rule = $photos[$i]["Photo"]["access_rule"];
                $author_user_id = $photos[$i]["Photo"]["author_user_id"];

                if ($access_rule == 4) {
                    if (!($this->session->get("authenticated") && ($author_user_id == $this->session->get("user_id")))) {
                        unset($photos[$i]);
                    }
                } else if ($access_rule == 3) {
                    if (!$this->session->get("authenticated")) {
                        unset($photos[$i]);
                    }

                    if (!$User->follows($this->session->get("user_id"), $author_user_id) && ($author_user_id != $this->session->get("user_id"))) {
                        unset($photos[$i]);
                    }
                } else if ($access_rule == 2) {
                    if (!$this->session->get("authenticated")) {
                        unset($photos[$i]);
                    }
                }
            }

            $photos = array_values($photos);

            $this->set("photo_result", $photos);
        }

        $this->set("title", "Search");
    }

}
